package io.zhengsh.order.controller;

import io.zhengsh.order.dto.OrderDto;
import io.zhengsh.order.dto.PaymentDto;
import io.zhengsh.order.dto.RefundOrderDto;
import io.zhengsh.order.dto.RefundPaymentDto;
import io.zhengsh.order.entity.OrderEntity;
import io.zhengsh.order.feign.PaymentFeign;
import io.zhengsh.order.mapper.OrderEntityMapper;
import io.zhengsh.order.service.OrderService;
import io.zhengsh.order.vo.OrderVo;
// import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhengsh
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentFeign paymentFeign;
    @Autowired
    private OrderEntityMapper orderEntityMapper;

    @GetMapping("/update")
    public OrderVo updateOrder(@Validated OrderDto orderDto) {

        for (int i = 0; i < 10; i++) {
            OrderEntity order = new OrderEntity();
            order.setOrderCode("OR000" + i);
            order.setOid((long) i);
            orderEntityMapper.insertSelective(order);
        }

        OrderVo orderVo = new OrderVo();
        orderVo.setId(100L);
        orderVo.setId(100L);

        return orderVo;
    }

    @GetMapping("/create")
    public OrderVo createOrder(@Validated OrderDto orderDto) {
        log.info("uri:/order/create lang:{}", LocaleContextHolder.getLocale().getLanguage());
        OrderVo orderVo = new OrderVo();
        orderVo.setId(1L);
        orderDto.setCode("ORT0000001");

        PaymentDto paymentDto = new PaymentDto();
        paymentDto.setId(orderDto.getId());
        paymentDto.setCode(orderDto.getCode());
        long start = System.currentTimeMillis();
        paymentFeign.create(paymentDto);
        log.info("uri:/order/create paymentFegin.create cost: {} ms", System.currentTimeMillis() - start);


        return orderVo;
    }

    @GetMapping("/refund")
    public Boolean refundOrder(@Validated RefundOrderDto refundDto) {
        log.info("uri:/order/refund orderCode:{}", refundDto.getOrderCode());
        RefundPaymentDto refundPaymentDto = new RefundPaymentDto();
        BeanUtils.copyProperties(refundDto, refundPaymentDto);
        paymentFeign.refund(refundPaymentDto);
        return Boolean.TRUE;
    }


    @GetMapping("/get/{id}")
    public OrderVo get(@PathVariable Long id) {
        return orderService.get(id);
    }
}
